
import { QuerySchema } from './QuerySchema';
import { MySQLSchema } from './schema/MySQLSchema';
import { PostgreSQLSchema } from './schema/PostgreSQLSchema';

import {Sequelize} from '@sequelize/core'

/**
 * 支持数据库类型
 */
export enum DBType{
    mysql='mysql', postgresql='postgres'
} 

// 

const conf = (dialect: string, config: any) : {}=>{
    return {
        dialect: dialect,
        database: config.database,
        username: config.user,
        password: config.password,
        host: config.host,
        port: config.port
    }
}

export class DB {
    instance;
    schema: QuerySchema;
    constructor(datasource: any,dbType?){
        dbType = datasource.db_type || DBType.mysql;
        this.init(dbType, datasource);
    }
    async query(sql: string, params?) {
        return await this.instance.query(sql,params);
    }

    /**
     * 获取数据库实例
     * @param dbType 支持数据库类型
     */
     init(dbType: DBType, datasource: {}){
        let instance : any;
        let schema : QuerySchema;
        
        switch (dbType) {
            case DBType.mysql:
                instance = new Sequelize(conf(DBType.mysql, datasource))
                schema = new MySQLSchema()
                break;
            case DBType.postgresql:
                instance = new Sequelize(conf(DBType.postgresql, datasource))
                schema = new PostgreSQLSchema()
                break;
            default:
                break;
        }
        this.instance = instance;
        this.schema = schema;
    }
}